package controllers

import (
	"../../../deps/lessgo/pagelet"
	"../../../deps/lessgo/utils"
	"../../../deps/lessgo/utilx"
	"../../base"
	"../../store"
	"io"
	"strconv"
	"strings"
)

type Stats struct {
	*pagelet.Controller
}

func (c Stats) BucketsAction() {

	c.AutoRender = false

	rsp := map[string]interface{}{
		"action": "stats.buckets",
	}

	defer func() {
		if rspj, err := utils.JsonEncode(rsp); err == nil {
			io.WriteString(c.Response.Out, rspj)
		}
	}()

	buckets := strings.Split(c.Params.Get("buckets"), ",")

	data := []interface{}{}
	for _, bucketName := range buckets {

		rs, err := store.NodeGet("/sys/bs/" + bucketName)
		if err != nil {
			continue
		}

		var b base.Bucket
		err = rs.ReplyJson(&b)
		if err == nil && b.Name != "" {

			rsState, _ := store.Cmd("HMGET", store.NodeData+bucketName,
				store.NodeSepNum, store.NodeSepSize).List()
			rsStateKeys, _ := strconv.ParseInt(rsState[0], 10, 64)
			rsStateSize, _ := strconv.ParseInt(rsState[1], 10, 64)

			rsKeys, _ := store.Cmd("SMEMBERS", "sys:b2ak:"+b.Name).List()

			data = append(data, map[string]interface{}{
				"name":          b.Name,
				"desc":          b.Desc,
				"dataSize":      b.DataSize,
				"stateDataKeys": rsStateKeys,
				"stateDataSize": rsStateSize,
				"accessKeys":    len(rsKeys),
				"created":       utilx.TimeParse(b.Created, "atom"),
				"updated":       utilx.TimeParse(b.Updated, "atom"),
			})
		}
	}

	rsp["data"] = data
}
